|
|
|
|
|
|
|
|
As you can see in this example and in others in the book, arrays and For loops are often used together. A For loop provides an easy way of looking at or processing each element of an array because the counter variable can be used as the array index.  |
|
|
|
|
|
|
CAUTION
|
|
|
|
|
Never reset the value of the counter variable inside a For loop. Doing so can cause an infinite loop. |
|
|
|
|
|
|
|
|
|
|
Typically, you will want your For loop to run through all the values of the counter variable. However, sometimes you might want the loop to terminate early. To do so, simply place an Exit For statement at the point in your loop where you want the loop to stop. The Exit For statement is typically associated with an If statement that determines whether the loop needs to be exited. In the following sample code from a trivia game, the player's score is examined after each question. If the score dips below zero, no more questions are asked. |
|
|
|
|
|
|
|
|
For i = 1 To nNumQuestions
Call AskAQuestion
If bPlayerWasRight Then
nScore = nScore + nQValue
Else
nScore = nScore - nQValue
End If
If nScore <= 0 Then Exit For
Next i |
|
|
|
|
|
|
|
|
The key feature of a conditional loop is, of course, the condition. The condition is any expression that can return either a True or a False value. It can be a function, such as EOF; the value of a property, such as the Value property of an Option button; or an expression, such as numval < 15. The two basic types of conditional loops are the Do While loop, which repeats while the condition is True, and a Do Until loop, which repeats until the condition is True. |
|
|
|
|
|
|
|
|
|
EOF stands for End-Of-File. The EOF function returns True if you have reached the end of a file or recordset.  |
|
|
|
|
|
|
|
|
|
|
Using Do While Statements |
|
|
|
|
|
|
|
|
The keyword While in the Do While statement tells the program that the loop will be repeated while the condition expression is True. When the condition in a Do While loop becomes false, the program moves on to the next statement after the Loop statement. |
|
|
|
|
|
|
|
|
You can use two forms of the Do While loop. The difference between the two is the placement of the condition. You can place the condition either at the beginning of the loop or at the end. |
|
|
|
|
|
|
|
|
The first form of the Do While loop places the condition at the beginning of the loop, as shown in the following example. This code repeats the steps while records are available in the recordset. |
|
|
|
|
|